import { defineStore } from 'pinia'
import { useAuthStore } from '@/store/auth'
import webSocketService from '@/utils/webSocket'
import api from '@/utils/api'

// 聊天API方法
export const getChatHistory = (otherUserId, page = 1, pageSize = 20) => {
  return api.get('/api/chat/history', {
    params: { otherUserId, page, pageSize }
  })
}

export const getUnreadChatCount = () => {
  return api.get('/api/chat/unread/count')
}

export const getRecentChatList = () => {
  return api.get('/api/chat/recent')
}

export const useChatStore = defineStore('chat', {
  state: () => ({
    chatHistory: {}, // 聊天历史：{ otherUserId: { messages: [], page: 1, hasMore: true } }
    recentChats: [], // 最近聊天列表
    currentChatUserId: null, // 当前聊天对象ID
    isLoading: false, // 加载状态
    error: null, // 错误信息
    unreadCount: 0 // 未读聊天消息数
  }),
  actions: {
    // 1. 获取聊天历史（分页+去重）
    async fetchChatHistory(otherUserId, forceRefresh = false) {
      const authStore = useAuthStore()
      if (!authStore.user?.id || !otherUserId) return []

      const page = forceRefresh ? 1 : (this.chatHistory[otherUserId]?.page || 1)
      this.isLoading = true
      this.error = null

      try {
        const response = await getChatHistory(otherUserId, page, 20)
        const messages = response.data || []
        const messageIds = new Set() // 用于去重

        // 去重当前页消息
        const uniqueMessages = messages.filter(msg => {
          if (messageIds.has(msg.id)) return false
          messageIds.add(msg.id)
          return true
        })

        // 初始化/更新聊天历史
        if (!this.chatHistory[otherUserId]) {
          this.chatHistory[otherUserId] = { messages: [], page: 1, hasMore: true }
        }

        if (forceRefresh) {
          this.chatHistory[otherUserId] = {
            messages: uniqueMessages,
            page: 1,
            hasMore: uniqueMessages.length >= 20
          }
        } else {
          // 合并历史消息并去重（避免重复加载）
          const allMessageIds = new Set(this.chatHistory[otherUserId].messages.map(m => m.id))
          const newUniqueMessages = uniqueMessages.filter(msg => !allMessageIds.has(msg.id))
          
          this.chatHistory[otherUserId] = {
            messages: [...this.chatHistory[otherUserId].messages, ...newUniqueMessages],
            page,
            hasMore: uniqueMessages.length >= 20
          }

          // 更新下一页页码
          if (this.chatHistory[otherUserId].hasMore) {
            this.chatHistory[otherUserId].page++
          }
        }

        this.currentChatUserId = otherUserId
        return this.chatHistory[otherUserId].messages
      } catch (error) {
        this.error = error.response?.data?.msg || '获取聊天历史失败'
        console.error('获取聊天历史失败:', error)
        return []
      } finally {
        this.isLoading = false
      }
    },

    // 2. 获取最近聊天列表
    async fetchRecentChats() {
      this.isLoading = true
      this.error = null

      try {
        const response = await getRecentChatList()
        const recentChats = response.data || []
        // 去重最近聊天列表（按对方用户ID去重）
        const chatMap = new Map()
        recentChats.forEach(chat => {
          chatMap.set(chat.otherUserId, chat)
        })
        this.recentChats = Array.from(chatMap.values())
        return this.recentChats
      } catch (error) {
        this.error = error.response?.data?.msg || '获取最近聊天列表失败'
        console.error('获取最近聊天列表失败:', error)
        return []
      } finally {
        this.isLoading = false
      }
    },

    // 3. 获取未读聊天消息数
    async fetchUnreadCount() {
      try {
        const response = await getUnreadChatCount()
        this.unreadCount = response.data || 0
        return this.unreadCount
      } catch (error) {
        this.error = error.response?.data?.msg || '获取未读消息数失败'
        console.error('获取未读消息数失败:', error)
        return 0
      }
    },

    // 4. 发送聊天消息（WebSocket）
    sendChatMessage(otherUserId, content) {
      const authStore = useAuthStore()
      if (!authStore.user?.id || !webSocketService.isConnected || !content.trim()) {
        return false
      }

      const message = {
        senderId: authStore.user.id,
        receiverId: otherUserId,
        content: content.trim()
      }

      // 发送WebSocket消息
      const success = webSocketService.sendMessage('/app/chat/send', message)
      if (success) {
        // 本地预渲染（优化体验）
        const savedMessage = {
          ...message,
          id: Date.now(), // 临时ID（后端返回后会替换）
          createdAt: new Date().toISOString(),
          isRead: false,
          senderUser: {
            id: authStore.user.id,
            nickname: authStore.user.nickname,
            avatarUrl: authStore.user.avatarUrl
          }
        }
        this.addChatMessage(savedMessage)
      }
      return success
    },

    // 5. 标记聊天消息已读（WebSocket）
    markChatAsRead(messageId) {
      if (!webSocketService.isConnected || !messageId) return false
      return webSocketService.sendMessage('/app/chat/read', { messageId })
    },

    // 6. 新增聊天消息（WebSocket推送后调用）
    addChatMessage(message) {
      const authStore = useAuthStore()
      if (!authStore.user?.id || !message) return

      const { senderId, receiverId, id: messageId } = message
      const otherUserId = senderId === authStore.user.id ? receiverId : senderId

      // 初始化聊天历史
      if (!this.chatHistory[otherUserId]) {
        this.chatHistory[otherUserId] = {
          messages: [],
          page: 1,
          hasMore: true
        }
      }

      // 去重：排除临时ID + 已存在的ID
      const isDuplicate = this.chatHistory[otherUserId].messages.some(m => {
        // 临时ID（Date.now()）允许重复（后端返回后替换），其他ID严格去重
        return m.id !== Date.now() && m.id === messageId
      })
      if (isDuplicate) return

      // 添加消息
      this.chatHistory[otherUserId].messages.push(message)
      // 更新未读计数（收到的消息且未读）
      if (receiverId === authStore.user.id && !message.isRead) {
        this.unreadCount++
      }
    },

    // 7. 切换当前聊天对象
    setCurrentChatUserId(otherUserId) {
      const authStore = useAuthStore()
      if (!authStore.user?.id || this.currentChatUserId === otherUserId) return

      this.currentChatUserId = otherUserId
      // 切换时标记未读消息为已读
      if (this.chatHistory[otherUserId]) {
        const unreadMessages = this.chatHistory[otherUserId].messages.filter(
          m => m.receiverId === authStore.user.id && !m.isRead
        )
        // 批量标记已读（避免多次调用WebSocket）
        if (unreadMessages.length > 0) {
          unreadMessages.forEach(m => this.markChatAsRead(m.id))
          // 本地更新未读状态和计数
          unreadMessages.forEach(m => {
            m.isRead = true
          })
          this.unreadCount = Math.max(0, this.unreadCount - unreadMessages.length)
        }
      }
    }
  }
})